//
//  JSQKeyView.m
//  Conversation
//
//  Created by C_HAO on 15/12/14.
//  Copyright © 2015年 CHAOO. All rights reserved.
//

#import "JSQKeyView.h"
#import "DAKeyboardControl.h"
#import "NSAttributedString+Emotion.h"

static void *kJSQKeyValueObservingContext = &kJSQKeyValueObservingContext;

@interface JSQKeyView () <JSQEmoticonViewDelegate, JSQKeyInputToolbarDelegate, UITextViewDelegate>

@property(nonatomic, strong) NSLayoutConstraint *JSQKeyViewAttributeBottom;

@property(nonatomic, weak) UIView *view;

@property (weak, nonatomic) IBOutlet JSQKeyInputToolbar *toolbar;

@property (weak, nonatomic) IBOutlet JSQEmoticonView *emoticonView;

@property (nonatomic, copy) void (^content)(NSString *string, NSAttributedString *attributedString);

@property (nonatomic, assign) BOOL marker;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolbarTop;

@end

@implementation JSQKeyView

static JSQKeyView *_JSQKeyView;

+ (void)showKeyboardView:(UIView *)view inputContent:(void (^)(NSString *string, NSAttributedString *attributedString))content {
    _JSQKeyView = [[[NSBundle mainBundle] loadNibNamed:@"JSQKeyView" owner:nil options:nil] firstObject];

    if (_JSQKeyView) {
        _JSQKeyView.content = content;

        _JSQKeyView.view = view;

        [_JSQKeyView.view addSubview:_JSQKeyView];

        _JSQKeyView.translatesAutoresizingMaskIntoConstraints = NO;

        [_JSQKeyView.view addConstraint:[NSLayoutConstraint constraintWithItem:_JSQKeyView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:_JSQKeyView.view attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];

        [_JSQKeyView.view addConstraint:[NSLayoutConstraint constraintWithItem:_JSQKeyView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:_JSQKeyView.view attribute:NSLayoutAttributeRight multiplier:1 constant:0]];

        _JSQKeyView.JSQKeyViewAttributeBottom = [NSLayoutConstraint constraintWithItem:_JSQKeyView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_JSQKeyView.view attribute:NSLayoutAttributeBottom multiplier:1 constant:175];
        [_JSQKeyView.view addConstraint:_JSQKeyView.JSQKeyViewAttributeBottom];

        [_JSQKeyView.view addConstraint:[NSLayoutConstraint constraintWithItem:_JSQKeyView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:219]];

        [_JSQKeyView.view updateConstraints];

        __block typeof(_JSQKeyView) VC = _JSQKeyView;
        [_JSQKeyView addKeyboardNonpanningWithActionHandler:^(CGRect keyboardFrameInView, BOOL opening, BOOL closing) {
            if (closing) {
                VC.JSQKeyViewAttributeBottom.constant = 175;

                if (!VC.marker) {
                    [VC removeFromSuperview];
                }
            } else {
                VC.JSQKeyViewAttributeBottom.constant = 175 - CGRectGetHeight(keyboardFrameInView);
            }

            [VC.view updateConstraints];
        }];
        _JSQKeyView.emoticonView.delegate = _JSQKeyView;
        _JSQKeyView.toolbar.inputToolbarDelegate = _JSQKeyView;
        _JSQKeyView.toolbar.keyboardView.messagesTextView.delegate = _JSQKeyView;
        [_JSQKeyView.toolbar.keyboardView.messagesTextView becomeFirstResponder];

        [_JSQKeyView jsq_addObservers];
    }
}

+ (void)hide {
    [_JSQKeyView jsq_removeObservers];
    [_JSQKeyView removeFromSuperview];
    _JSQKeyView = nil;
}

- (void)keyInputToolbar:(JSQKeyInputToolbar *)keyInputToolbar {
    _marker = YES;
    [self.toolbar.keyboardView.messagesTextView resignFirstResponder];
    [UIView animateWithDuration:0.5 animations:^{
        self.JSQKeyViewAttributeBottom.constant = 0;
        [_view updateConstraints];
        _marker = NO;
    }];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        self.content((textView.attributedText) ? [textView.attributedText plainEmotionString] : textView.text, textView.attributedText);
        [JSQKeyView hide];
        return NO;
    }

    return YES;
}

#pragma mark - Utilities

- (void)jsq_addObservers {
    [self.toolbar.keyboardView.messagesTextView addObserver:self
                                                 forKeyPath:NSStringFromSelector(@selector(contentSize))
                                                    options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                                                    context:kJSQKeyValueObservingContext];
}

- (void)jsq_removeObservers {
    @try {
        [self.toolbar.keyboardView.messagesTextView removeObserver:self
                                                        forKeyPath:NSStringFromSelector(@selector(contentSize))
                                                           context:kJSQKeyValueObservingContext];
    }@catch (NSException *__unused exception) {
    }
}

#pragma mark - Key-value observing

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == kJSQKeyValueObservingContext) {
        if ((object == self.toolbar.keyboardView.messagesTextView)
            && [keyPath isEqualToString:NSStringFromSelector(@selector(contentSize))]) {
            CGSize oldContentSize = [[change objectForKey:NSKeyValueChangeOldKey] CGSizeValue];
            CGSize newContentSize = [[change objectForKey:NSKeyValueChangeNewKey] CGSizeValue];

            CGFloat dy = newContentSize.height - oldContentSize.height;

            _toolbarTop.constant = -dy;

            [self updateConstraints];
            [_view updateConstraints];
        }
    }
}

- (void)selectTheFace:(NSString *)face {
    NSAttributedString *attributedText = _toolbar.keyboardView.messagesTextView.attributedText;

    if (attributedText && ![attributedText.string isEqualToString:@""]) {
        NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithAttributedString:_toolbar.keyboardView.messagesTextView.attributedText];
        [attributed appendAttributedString:[[NSAttributedString alloc] initWithString:face]];
        _toolbar.keyboardView.messagesTextView.attributedText = attributed;
    } else {
        NSString *text = [_toolbar.keyboardView.messagesTextView.text stringByAppendingString:face];
        NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:text];
        _toolbar.keyboardView.messagesTextView.attributedText = attributed;
    }
}

+ (NSString *)interceptCharacter:(NSString *)character characterLength:(NSInteger)lenght {
    if (character.length <= lenght) {
        return character;
    }

    NSError *error;
    NSString *regulaStr = @"~:[a-z][0-9]~";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:character options:0 range:NSMakeRange(0, [character length])];

    for (NSTextCheckingResult *match in arrayOfAllMatches) {
        NSRange matchRange = NSMakeRange(match.range.location, match.range.length);
        if (matchRange.location > lenght) {
            return [character substringToIndex:lenght];
        } else if ((matchRange.location + matchRange.length) > lenght) {
            return [character substringToIndex:matchRange.location];
        }
    }
    return [character substringToIndex:lenght];
}

@end
